package Leetcode;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class numIslands {
    int[][] step = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
    public void dfs(char[][] grid,boolean[][] visit, int x, int y){
        visit[x][y] = true;
        for (int i = 0; i < 4; i++) {
            int nextX = x + step[i][0];
            int nextY = y + step[i][1];
            if (nextX < 0 || nextY < 0 || nextX >= grid.length || nextY >= grid[0].length){
                continue;
            }
            if (!visit[nextX][nextY] && grid[nextX][nextY] == '1'){
                dfs(grid, visit, nextX, nextY);
            }
        }
    }
    public int numIslands(char[][] grid) {
        int rows = grid.length;
        int ceil = grid[0].length;
        boolean[][] visit = new boolean[rows][ceil];
        int result = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < ceil; j++) {
                if (grid[i][j] == '1' && !visit[i][j]){
                    result++;
                    dfs(grid, visit, i, j);
                }
            }
        }
        return result;
    }
}
